Source Code Viewer - Example 9 - GBPConverter

package name.matthewgreet.example9.util;

import java.math.BigDecimal;
import name.matthewgreet.strutscommons.annotation.Required.MessageType;
import name.matthewgreet.strutscommons.policy.AbstractCustomConverterSupport;
import name.matthewgreet.strutscommons.policy.ConversionResult;

/**
 * Custom converter that converts an amount in pound sterling into a whole number of pence.  An amount that's a fraction
 * of a pence is an error.
 */
public class GBPConverter extends AbstractCustomConverterSupport<Integer> {
    @Override
    public Class<Integer> getRecipientClass() {
        return Integer.class;
    }
    
	@Override
	public String format(Integer unformattedValue) {
		int pounds, remainder;
		
		pounds = unformattedValue.intValue() / 100;
		remainder = unformattedValue.intValue() % 100;
		return pounds + "." + remainder;
	}

	@Override
	public ConversionResult<Integer> convert(String fieldValue, Class<? extends Integer> recipientClass) {
		BigDecimal decimalValue;
		int result;
		
		try {
			decimalValue = new BigDecimal(fieldValue);
			if (decimalValue.scale() > 2) {
				return ConversionResult.makeFailureWithMessageResult("Price cannot have fractions of a pence", MessageType.ERROR);
			}
			result = decimalValue.movePointRight(2).intValue();
			return ConversionResult.makeSuccessResult(result);
		}
		catch (NumberFormatException  e) {
			return ConversionResult.makeFailureWithMessageResult("Price is not a number", MessageType.ERROR);
		}
	}

}